package org.blueoxygen.dao;

import java.util.List;
import org.blueoxygen.cimande.commons.LogInformation;
import org.blueoxygen.cimande.persistence.hibernate.dao.HibernatePersistenceDaoManager;
import org.blueoxygen.cimande.security.User;
import org.blueoxygen.entity.Absen;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * @author Nety Herawaty
 * 
 */

@Repository
public class AbsenDao extends HibernatePersistenceDaoManager<Absen> {

	public void simpanAbsen(Absen absen) {
		if (absen == null)
			return;

		if (absen.getId() == null) {
			buatAbsen(absen);
		} else if (absen.getId().trim().equalsIgnoreCase("")) {
			buatAbsen(absen);
		} else {
			absen.getLogInformation()
					.setLastUpdateBy(getCurrentUser().getId());
			absen.getLogInformation().setLastUpdateDate(getCurretTime());

			merge(absen);
		}
	}

	public long getPersonCountByCriteria(String fname, String lname) {
		Criteria criteria = getPersonCriteria(fname, lname);
		criteria.setProjection(Projections.rowCount());

		return new Long(criteria.uniqueResult() + "");
	}

	@SuppressWarnings("unchecked")
	public List<Absen> getAbsenByCriteria(String namad, String namab,
			int limit, int page) {

		return getPersonCriteria(namad, namab).setMaxResults(limit)
				.setFirstResult((page - 1) * limit).list();
	}

	private Criteria getPersonCriteria(String namad, String namab) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				Absen.class);

		criteria.add(Restrictions.like("namad", namad, MatchMode.ANYWHERE));
		criteria.add(Restrictions.like("namab", namab, MatchMode.ANYWHERE));
	
		return criteria;
	}

	private void buatAbsen(Absen absen) {
		User user = getCurrentUser();
		LogInformation logInformation = new LogInformation();
		logInformation.setCreateBy(user.getId());
		logInformation.setCreateDate(getCurretTime());
		logInformation.setLastUpdateBy(user.getId());
		logInformation.setLastUpdateDate(getCurretTime());

		absen.setId(null);
		absen.setLogInformation(logInformation);

		persist(absen);
	}
}